import shutil
import os
import logging
import sys
import re

logger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)


def scan_templates(templates_dir):
    templates = {}
    for file in os.listdir(templates_dir):
        fn, ext = os.path.splitext(file)
        if not fn or not ext:
            continue
        full = os.path.join(templates_dir, file)
        templates[ext.lower()] = full
        print(f'扩展名[{ext}]使用模板 {full}')
    return templates


def process_files_in_txt(txt_file, des_dir, templates_dir=os.getcwd()):
    """
    读txt文件，并按每行要求在指定文件夹下创建文件或文件夹
    :param txt_file: txt输入文件
    :param des_dir: 指定文件夹
    :param templates_dir: 模板文件夹，默认为当前路径
    :return:
    """
    print(f'模板文件夹:{templates_dir}')
    os.makedirs(des_dir, exist_ok=True)
    templates = scan_templates(templates_dir)
    with open(txt_file, 'r', encoding='utf8', errors='ignore') as f:
        for line in f.readlines():
            file = line.strip()
            fn, ext = os.path.splitext(file)
            ext = ext.lower()
            if re.match(r'.+\.[a-zA-Z0-9]{3,4}', file):
                if ext in templates.keys():
                    template_file = templates[ext]
                    des_full = os.path.join(des_dir, file)
                    shutil.copy(template_file, des_full)
                    print(f'复制 {template_file} 到 {des_dir}')
                else:
                    print(f'未找到{file}的模板, 跳过...')
            else:
                des_full_d = os.path.join(des_dir, file)
                os.makedirs(des_full_d, exist_ok=True)
                print(f'创建文件夹 {des_full_d}')


if __name__ == '__main__':
    process_files_in_txt(r"D:\dl\样例数据\给定文件夹.txt",
                         r"D:\dl\output",
                         )
